<template>
    <div class="uploadbottom">
        <!-- <div class="uploadleft">
			<el-input placeholder="情输入分组名称" v-model="input1" class="searchinput1">
				<i slot="suffix" class="el-input__icon el-icon-search" style="cursor: pointer;"></i>
			</el-input>
			<el-button class="showallbtn" size="medium" @click="showAllVideo">全部视频</el-button>
			<el-tree :data="data" @node-click="handleNodeClick" class="uploadtree" highlight-current
				:filter-node-method="filterNode" ref="tree"></el-tree>
		</div> -->
        <div class="uploadright">
            <div class="uploadmaintop">
                <photoUpload
                    ref="upload"
                    v-model="fileList"
                    class="create-folder reset"
                    model="2"
                    @on-close="handleCloseUpload"
                    :callbackQuery="getVideoData"
                ></photoUpload>

                <!-- <el-button size="small" type="primary" onclick="document.getElementById('upload3').click()">上传视频</el-button> -->
                <!-- <el-upload
                    ref="upload"
                    action
                    :show-file-list="false"
                    multiple
                    :limit="100"
                    :http-request="upLoadData"
                    :auto-upload="true"
                   
                >
			
				<el-button type="primary" icon="el-icon-upload2"
                  >上传视频</el-button
                >
              </el-upload> -->

                <!-- <input type="file" name="upload3" id="upload3" style="display: none" multiple="multiple" @change="selFile($event)" />
                <i :class="liststyle ? 'el-icon-s-order uploadqiehuan' : 'el-icon-s-grid uploadqiehuan'" @click="clickListStyle"></i> -->
                <!-- <el-select v-model="value" placeholder="选择排序" class="el-menus" @change="handleSelect">
					<el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value">
					</el-option>
				</el-select> -->
                <!-- <el-input placeholder="查找图片名称" v-model="input2" class="searchinput2">
					<i slot="suffix" class="el-input__icon el-icon-search" style="cursor: pointer;"
						@click="searchVideoName"></i>
				</el-input> -->
            </div>
            <div class="uploadmainfile">
                <transition name="el-fade-in-linear">
                    <el-table
                        ref="multipleTable"
                        :data="tableData"
                        tooltip-effect="dark"
                        style="width: 100%"
                        @selection-change="handleSelectionChange"
                        height="460"
                        v-if="liststyle"
                    >
                        <el-table-column type="selection" width="30"> </el-table-column>
                        <el-table-column label="图片" width="300">
                            <template slot-scope="scope">
                                <div @click="playvideo(scope.row.file_path)">
                                    <el-image
                                        style="width: 50px; height: 30px; display: inline-block"
                                        :src="scope.row.src"
                                        fit="contain"
                                    ></el-image>
                                    <div style="display: inline-block; padding-left: 10px">
                                        <p class="text_over">{{ scope.row.base_name }}</p>
                                        <!-- <p>{{ scope.row.time }} {{ scope.row.resolution }}</p> -->
                                    </div>
                                    <el-progress
                                        v-if="progressFlag && (scope.$index < count ? true : false)"
                                        :percentage="loadProgress[scope.$index]"
                                    >
                                    </el-progress>
                                </div>
                            </template>
                        </el-table-column>
                        <el-table-column label="大小" width="120">
                            <template slot-scope="scope">
                                <span>{{ scope.row.file_size }}</span>
                            </template>
                        </el-table-column>
                        <el-table-column prop="create_time" label="上传时间" show-overflow-tooltip align="right"> </el-table-column>
                    </el-table>
                </transition>
                <transition name="el-fade-in">
                    <el-row v-show="!liststyle" class="cardfile" :gutter="10">
                        <el-checkbox-group @change="handleCheckedCardsChange" v-model="multipleSelection">
                            <el-col :span="6" v-for="(item, index) in tableData" :key="index" style="margin-bottom: 20px">
                                <el-card :body-style="{ padding: '0px' }">
                                    <img :src="item.src" class="image" height="120px" @click="playvideo(item.file_path)" />
                                    <div style="padding: 14px">
                                        <el-checkbox :label="item" class="elcheckbox">{{ item.base_name }} </el-checkbox
                                        ><span style="margin-left: 5px">{{ item.base_name }}</span>
                                        <div class="bottom clearfix">
                                            <time class="time">{{ item.time }} {{ item.resolution }}</time>
                                            <el-button type="text" class="button">{{ item.size }}M</el-button>
                                        </div>
                                    </div>
                                </el-card>
                                <el-progress v-if="progressFlag && (index < count ? true : false)" :percentage="loadProgress[index]">
                                </el-progress>
                            </el-col>
                        </el-checkbox-group>
                    </el-row>
                </transition>
            </div>
            <div class="uploadmainbottom">
                <!-- <el-checkbox @change="allChoose" class="elcheckbox" v-model="checkAll" v-if="liststyle">当页全选 </el-checkbox>
                <el-checkbox v-model="checkAll" @change="handleCheckAllChange" class="elcheckbox" v-if="!liststyle">当页全选 </el-checkbox>
                <el-link type="danger" class="deletevideo" @click="deleteVideo">删除</el-link> -->
                <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="page"
                    :page-sizes="[10, 20, 50, 100]"
                    :page-size="limit"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="total"
                    class="elpagination"
                >
                </el-pagination>
            </div>
        </div>
        <el-dialog title="视频" :visible.sync="videoplayshow" width="50%" :before-close="handleClose" append-to-body>
            <div id="J_prismPlayer"></div>
        </el-dialog>
    </div>
</template>

<script>
import uploadfileMixin from '@/mixin/uploadossfile.js';
import deletefileMixin from '@/mixin/deleteossfile.js';
import showfileMixin from '@/mixin/showossfile.js';
import photoUpload from '@/components/photoUpload';

import { put } from '@/utils/tools';

import {
    fenZuData,
    insertUploadVideo,
    showUploadVideo,
    deleteUploadVideo,
    houtairesbucket,
    api_getPolicy,
    api_uploadCallback,
    api_getAttachmentList
} from '../../api/index';
import { call } from 'file-loader';
export default {
    components: {
        photoUpload
    },
    // filters: {
    //     formatStr(str) {
    //         if (str.length > 10) {
    //             return str.toString().substr(0, 10) + '...';
    //         } else {
    //             return str;
    //         }
    //     }
    // },
    mixins: [uploadfileMixin, deletefileMixin, showfileMixin],
    data() {
        return {
            fileList: [],
            input1: '',
            input2: '',
            data: [],
            liststyle: 1,
            options: [
                {
                    value: '选项1',
                    label: '按文件名（a-z）'
                },
                {
                    value: '选项2',
                    label: '按文件名（z-a）'
                },
                {
                    value: '选项3',
                    label: '文件大小（大-小）'
                },
                {
                    value: '选项4',
                    label: '文件大小（小-大）'
                },
                {
                    value: '选项5',
                    label: '上传时间（新-旧）'
                },
                {
                    value: '选项6',
                    label: '上传时间（旧-新）'
                }
            ],
            value: '',
            tableData: [
                // {
                //     name: '图片1',
                //     time: '00:00:34',
                //     size: '1.7',
                //     date: '2016-05-03 00:00:00',
                //     src: 'https://shadow.elemecdn.com/app/element/hamburger.9cf7b091-55e9-11e9-a976-7f4d0b07eef6.png',
                //     resolution: '400*400'
                // }
            ],
            checkAll: false,
            multipleSelection: [],
            count: 0,
            progressFlag: false,
            loadProgress: [],
            nodedata: '',
            page: 1,
            limit: 10,
            total: 0,
            node: 'all',
            sortid: '',
            order: '',
            videoplayshow: false,
            player: ''
        };
    },
    watch: {
        input1(val) {
            this.$refs.tree.filter(val);
        }
    },
    created() {
        this.getSortDir(); //得到分组
        this.showAllVideo(); //得到所有图片列表
    },
    methods: {
        handleCloseUpload() {
            this.fileList = [];
        },
        upLoadData(file) {
            this.upLoad(file).then((res) => {
                this.$message.success('上传成功');
            });
        },
        // 上传合同图片
        async upLoad(item) {
            console.log(item, 1111);
            let res = await api_getPolicy({
                type: 2,
                scene: 'edu_shop'
            });
            let baseurl = res.data.dir || '';
            let domain = res.data.domain || '';

            // item 是当前本地上传的这张图片
            // 随机命名
            var fileName = item.file.name; // 当前本地上传的这张图片的名称(没有时间日期)
            var date = new Date();
            var year = date.getFullYear();
            var month = date.getMonth() + 1;
            month = month < 10 ? '0' + month : month;
            var mydate = date.getDate();
            mydate = mydate < 10 ? '0' + mydate : mydate;
            this.baseurl = baseurl;
            // this.baseurl =
            //   "img/" + year + "/" + year + month + "/" + year + month + mydate + "/";
            // 这里是把时间+图片名称拼接起来形成一个新的图片上传至oss，目的是区别于本地图片的名称，避免名称相同会误删，同时便于查看oss上最新上传图片的时间点
            var filePath = this.baseurl + this.generateUniqueFileName() + fileName;

            var file = item.file; // 当前本地上传的这张图片
            let obj = {
                type: 2,
                base_name: file.name,
                file_path: domain + '/' + filePath,
                file_size: file.size,
                scene: 'edu_shop'
                // id: null,
                // live_id: this.orderObjs.live_id
            };
            return put(filePath, file).then(async (result) => {
                // 文件上传成功后，获取返回值中的文件名name，并把其放入fileList数组中，表示当前已上传的文件

                let res = await api_uploadCallback(obj);
                this.getVideoData();
                return obj;
            });
        },
        generateUniqueFileName() {
            let chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
            let fileName = '';
            for (let i = 0; i < 26; i++) {
                fileName += chars.charAt(Math.floor(Math.random() * chars.length));
            }
            // console.log(fileName)
            return fileName;
        },
        handleNodeClick(data) {
            //点击左边分组然后对应显示图片列表
            this.nodedata = data;
            console.log(this.nodedata);
            this.page = 1;
            if (data.pid == 0) {
                this.node = 'root';
            } else {
                this.node = 'children';
            }
            this.input2 = '';
            this.sortid = data.id;
            this.getVideoData();
        },
        handleSelect() {
            //选择排序对应显示排序列表
            this.page = 1;
            this.order = this.value;
            this.getVideoData();
        },
        handleSelectionChange(val) {
            //全选表格
            this.multipleSelection = val;
            if (val.length == this.tableData.length) {
                this.checkAll = true;
            } else if (val.length == 0) {
                this.checkAll = false;
            }
        },
        allChoose(val) {
            //全轩列表当前页
            if (val) {
                for (let i in this.tableData) {
                    this.$nextTick(() => {
                        this.$refs.multipleTable.toggleRowSelection(this.tableData[i], true);
                    });
                }
                this.multipleSelection = this.tableData;
            } else {
                this.$refs.multipleTable.clearSelection();
                this.multipleSelection = [];
            }
        },
        handleSizeChange(val) {
            //选择每页显示多少条
            this.limit = val;
            this.getVideoData();
            //console.log(`每页 ${val} 条`);
        },
        handleCurrentChange(val) {
            //显示当前页列表
            this.page = val;
            this.getVideoData();
            //console.log(`当前页: ${val}`);
        },
        handleCheckedCardsChange(value) {
            //如果卡片一个一个全部选中了，就勾选全部选中复选框
            this.multipleSelection = value;
            let checkedCount = value.length;
            this.checkAll = checkedCount === this.tableData.length;
            console.log(this.multipleSelection);
        },
        clickListStyle() {
            //切换显示样式列表或卡片
            if (this.liststyle) {
                //列表模式转卡片模式
                this.liststyle = false;
            } else {
                this.liststyle = true; //卡片模式转列表模式
                for (let i of this.multipleSelection) {
                    this.$nextTick(() => {
                        this.$refs.multipleTable.toggleRowSelection(i, true);
                    });
                }
            }
        },
        handleCheckAllChange(val) {
            //全选卡片当前页面复选框
            this.multipleSelection = val ? this.tableData : [];
        },
        getSortDir() {
            //得到分组目录
            fenZuData({
                typeid: 2
            }).then((res) => {
                var classifyList = res.data.list;
                for (let i = 0; i < classifyList.length; i++) {
                    this.data.push({
                        pid: '',
                        id: '',
                        label: '',
                        children: []
                    });
                    this.data[i].pid = classifyList[i].pid;
                    this.data[i].id = classifyList[i].id;
                    this.data[i].label = classifyList[i].title;
                    if (classifyList[i]._child) {
                        for (let j = 0; j < classifyList[i]._child.length; j++) {
                            this.data[i].children.push({
                                pid: classifyList[i]._child[j].pid,
                                id: classifyList[i]._child[j].id,
                                label: classifyList[i]._child[j].title,
                                plabel: classifyList[i].title
                            });
                        }
                    }
                }
                //console.log(this.data);
            });
        },
        async getVideoData() {
            //按一定条件得到上传图片列表
            // var res = await showUploadVideo({
            // 	node: this.node,
            // 	sortid: this.sortid,
            // 	page: this.page,
            // 	limit: this.limit,
            // 	search: this.input2,
            // 	order: this.order
            // });
            let obj = {
                type: 2,
                nums: this.limit,
                page: this.page,
                source_type: 'edu_shop'
            };
            let res = await api_getAttachmentList(obj);
            this.tableData = res.data.list;
            this.total = res.data.count;

            this.$emit('updateVideoTotal', this.total);
        },
        filterNode(value, data) {
            //分组过滤input
            if (!value) return true;
            return data.label.indexOf(value) !== -1;
        },
        async selFile(e) {
            //选择上传文件
            // if (!this.nodedata) {
            // 	this.$message.error('请创建分组后选择分组再上传！');
            // 	document.getElementById('upload3').value = "";
            // 	return;
            // }
            let files = e.target.files;
            for (let k = 0; k < files.length; k++) {
                const tmpvideo = files[k].name.split('.');
                const extvideoname = tmpvideo.pop();
                const extvideoList = ['mp4'];
                const isvideoValid = extvideoList.includes(extvideoname);
                if (!isvideoValid) {
                    var result = true;
                    break;
                } else {
                    var result = false;
                }
            }
            if (result) {
                this.$message.error('只能传视频文件!');
                return;
            }
            this.count = files.length;
            let filearr = [];
            for (let i = 0; i < files.length; i++) {
                const videoInfo = await getVideoPlayerInfo(files[i]);
                const { duration, width, height } = videoInfo;
                const imgsrc = await getVideoPoster(files[i], 200);
                filearr[i] = {
                    name: files[i].name,
                    size: (files[i].size / 1024 / 1024).toFixed(2),
                    createtime: await jsDateFormatter(new Date()),
                    resolution: width + '*' + height,
                    time: getTime(duration),
                    src: imgsrc
                };
                this.tableData.splice(0, 0, filearr[i]);
            }
            this.progressFlag = true;
            let username = localStorage.getItem('ms_username');
            let shopuuid = localStorage.getItem('shopuuid');
            var path = 'video/' + username + '/' + shopuuid + '/';
            for (let j = 0; j < files.length; j++) {
                let url = await this.fileUpload(files[j], path + files[j].name, j, this, houtairesbucket, 3); //上传到oss，3代表上传视频
                filearr[j].path = path;
                // filearr[j].path = url;

                console.log('url', url);

                if (files[j].size < 50 * 1024 * 1024) {
                    let res = await insertUploadVideo({
                        file: JSON.stringify(filearr[j]),
                        path,
                        //bucket,
                        houtairesbucket,
                        sortpid: 0,
                        sortid: 0
                    }); //插入数据库
                    //console.log(res);
                    if (res.code == -1) {
                        let filepath = path + files[j].name;
                        this.deleteMultiFile([filepath]);
                        this.$message.error('保存数据库出错了！');
                    } else if (res.code == -2) {
                        this.$message.error('请不要上传相同的文件');
                    }
                } else {
                    this.$message.error('请上传小于50M的文件');
                }
            }
            this.getVideoData();
            this.multipleSelection = [];
            this.checkAll = false;
        },
        async deleteVideo() {
            //删除图片
            //console.log(this.multipleSelection);
            if (this.multipleSelection.length == 0) {
                this.$message.error('请选择文件后再来删除');
                return;
            }
            this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(async () => {
                let pathname = [];
                let ids = [];
                for (let i = 0; i < this.multipleSelection.length; i++) {
                    pathname.push(this.multipleSelection[i].path + this.multipleSelection[i].name);
                    ids.push(this.multipleSelection[i].id);
                }
                ids = ids.toString();
                let deleteres = await deleteUploadVideo({
                    ids
                });
                //console.log(deleteres);
                if (deleteres.code == 1) {
                    const newItems = [...this.multipleSelection];
                    for (let j = 0; j < newItems.length; j++) {
                        let index = this.tableData.indexOf(newItems[j]);
                        if (index > -1) {
                            this.tableData.splice(index, 1);
                        }
                    }
                    this.multipleSelection = [];
                    this.deleteMultiFile(pathname, houtairesbucket);
                    this.getVideoData();
                } else {
                    this.$message.error('删除失败！');
                }
            });
        },
        showAllVideo() {
            //显示所有图片
            this.node = 'all';
            this.page = 1;
            this.input2 = '';
            this.getVideoData();
            //this.getVideoData();
        },
        searchVideoName() {
            //搜索指定的图片
            this.page = 1;
            this.getVideoData();
        },
        async playvideo(path) {
            //let path="video/admin/25/平面设计/室内设计/6781f56fd516a2be3ccf78de88d6ea81.mp4";
            this.videoplayshow = true;
            let res = await this.getSignatureUrl(path); //bucket默认xuejingres,暂时可以不填写
            var player = new Aliplayer(
                {
                    id: 'J_prismPlayer',
                    source: path, //播放地址，可以是第三方点播地址，或阿里云点播服务中的播放地址。
                    width: '100%',
                    height: '500px',
                    autoplay: true,
                    isLive: false,
                    rePlay: false,
                    playsinline: true,
                    preload: true,
                    controlBarVisibility: 'hover',
                    useH5Prism: true,
                    extraInfo: {
                        crossOrigin: 'anonymous'
                    },
                    skinLayout: [
                        {
                            name: 'bigPlayButton',
                            align: 'blabs',
                            x: 30,
                            y: 80
                        },
                        {
                            name: 'H5Loading',
                            align: 'cc'
                        },
                        {
                            name: 'errorDisplay',
                            align: 'tlabs',
                            x: 0,
                            y: 0
                        },
                        {
                            name: 'infoDisplay'
                        },
                        {
                            name: 'tooltip',
                            align: 'blabs',
                            x: 0,
                            y: 56
                        },
                        {
                            name: 'thumbnail'
                        },
                        {
                            name: 'controlBar',
                            align: 'blabs',
                            x: 0,
                            y: 0,
                            children: [
                                {
                                    name: 'progress',
                                    align: 'blabs',
                                    x: 0,
                                    y: 44
                                },
                                {
                                    name: 'playButton',
                                    align: 'tl',
                                    x: 15,
                                    y: 12
                                },
                                {
                                    name: 'timeDisplay',
                                    align: 'tl',
                                    x: 10,
                                    y: 7
                                },
                                {
                                    name: 'fullScreenButton',
                                    align: 'tr',
                                    x: 10,
                                    y: 12
                                },
                                {
                                    name: 'subtitle',
                                    align: 'tr',
                                    x: 15,
                                    y: 12
                                },
                                {
                                    name: 'setting',
                                    align: 'tr',
                                    x: 15,
                                    y: 12
                                },
                                {
                                    name: 'volume',
                                    align: 'tr',
                                    x: 5,
                                    y: 10
                                },
                                {
                                    name: 'snapshot',
                                    align: 'tr',
                                    x: 10,
                                    y: 12
                                }
                            ]
                        }
                    ]
                },
                function (player) {
                    //console.log("The player is created");
                    player.play();
                }
            );
            this.player = player;

            /* h5截图按钮, 截图成功回调 */
            player.on('snapshoted', function (data) {
                var pictureData = data.paramData.base64;
                var downloadElement = document.createElement('a');
                downloadElement.setAttribute('href', pictureData);
                var fileName = 'Aliplayer' + Date.now() + '.png';
                downloadElement.setAttribute('download', fileName);
                downloadElement.click();
                pictureData = null;
            });
        },
        handleClose() {
            this.player.dispose();
            this.videoplayshow = false;
        }
        // ,test() {
        // 	alert(1);
        // }
    }
};
</script>

<style lang="scss" scoped>
.uploadbottom {
    width: 98%;
    height: 550px;
    display: flex;
    margin-left: 10px;

    .uploadleft {
        border: 1px solid #ccc;
        width: 25%;
        height: 550px;
        text-align: center;

        .showallbtn {
            margin-top: 10px;
            width: 100%;
            border-left: none;
            border-right: none;
        }

        .searchinput1 {
            width: 90%;
            margin-top: 10px;
            display: inline-block;
        }

        .uploadtree {
            //padding-left: 10px;
            margin-top: 10px;
        }
    }

    .uploadright {
        margin-left: 15px;
        width: 100%;
        height: 550px;

        .uploadmaintop {
            height: 45px;
            width: 100%;
            line-height: 45px;
            position: relative;

            .el-menus {
                width: 160px;
                display: inline-block;
                margin-left: 3%;
            }

            .uploadqiehuan {
                line-height: 45px;
                margin-left: 25%;
                font-size: 22px;
                display: inline-block;
            }

            .searchinput2 {
                position: absolute;
                right: 0;
                width: 30%;
                margin-left: 1%;
                display: inline-block;
            }
        }

        .uploadmainfile {
            margin-top: 10px;

            .cardfile {
                height: 460px;
                overflow-y: scroll;

                .time {
                    font-size: 13px;
                    color: #999;
                }

                .bottom {
                    margin-top: 13px;
                    line-height: 12px;
                }

                .button {
                    padding: 0;
                    float: right;
                }

                .image {
                    width: 100%;
                    display: block;
                }

                .clearfix:before,
                .clearfix:after {
                    display: table;
                    content: '';
                }

                .clearfix:after {
                    clear: both;
                }
            }
        }

        .uploadmainbottom {
            margin-top: 10px;
            position: relative;
            height: 40px;

            .elcheckbox {
                position: absolute;
                left: 10px;
                top: 5px;
            }

            .deletevideo {
                position: absolute;
                left: 100px;
                top: 5px;
            }

            .elpagination {
                position: absolute;
                right: 0;
            }
        }
    }
}
</style>
